<?php

namespace App\HttpController\V1;

use App\Utility\Pool\MysqlPool;
use App\Utility\Pool\RedisPool;
use EasySwoole\Component\Pool\PoolManager;
use EasySwoole\EasySwoole\Config;

class BaseWithDb extends Base
{
    protected $db;
    protected $redis;
    protected $admin_url = ADMIN_URL;
    protected $api_url = API_URL;
    protected $video_url = QINIU_URL;
    protected $web_url = WEB_URL;

    function onRequest( ?string $action ): ?bool
    {
        $db = PoolManager::getInstance()->getPool( MysqlPool::class )->getObj( Config::getInstance()->getConf( 'MYSQL.POOL_TIME_OUT' ) );

        if ( $db ) {
            $this->db = $db;
        } else {
            //直接抛给异常处理，不往下
            throw new \Exception( 'url :' . $this->request()->getUri()->getPath() . ' error,Mysql Pool is Empty' );
        }

        $redis = PoolManager::getInstance()->getPool( RedisPool::class )->getObj( Config::getInstance()->getConf( 'REDIS.POOL_TIME_OUT' ) );
        if ( !empty($redis) ) {
            $this->redis = $redis;
            $this->redis->select(9);
        } else {
//            直接抛给异常处理，不往下
            throw new \Exception( 'url :' . $this->request()->getUri()->getPath() . ' error,Redis Pool is Empty' );
        }
        return parent::onRequest( $action ); // TODO: Change the autogenerated stub
    }

    protected function gc()
    {
        PoolManager::getInstance()->getPool( MysqlPool::class )->recycleObj( $this->db );
        PoolManager::getInstance()->getPool( RedisPool::class )->recycleObj( $this->redis );
        parent::gc();
    }

    protected function getDbConnection(): MysqlPoolObject
    {
        return $this->db;
    }

    protected function writeJson( $statusCode = 200, $result = null, $msg = null )
    {

        $data = Array(
            "status" => $statusCode,
            "data" => $result,
            "msg" => $msg
        );
        $this->response()->write( json_encode( $data) );
        $this->response()->withHeader( 'Content-type', 'application/json;charset=utf-8' );
        $this->response()->end();
        return false;
    }
}